<template>
  <div>
    <div style="margin-top: 15px;">
      <el-button size="mini" :type="status==0?'primary':''" round @click="statusQuery(-1)">全部</el-button>
      <el-button size="mini" :type="status==33?'primary':''" round @click="statusQuery(33)">未推送</el-button>
      <el-button size="mini" :type="status==34?'primary':''" round @click="statusQuery(34)">抽奖中</el-button>
      <el-button size="mini" :type="status==35?'primary':''" round @click="statusQuery(35)">已开奖</el-button>
    </div>
    <el-table :data="tableDataList" style="width: 100%;margin-top: 15px;" height="500" :header-cell-style="headerCellStyle" :cell-style="cellStyle">
      <template slot="empty">
        <p>暂无抽奖</p>
      </template>
      <el-table-column prop="id" align="center" label="序号" min-width="10%">
      </el-table-column>
      <el-table-column prop="name" :show-overflow-tooltip="true" align="center" label="抽奖名称" min-width="20%">
      </el-table-column>
      <el-table-column prop="prizeName" :show-overflow-tooltip="true" align="center" label="抽奖奖品" min-width="20%">
      </el-table-column>
      <el-table-column prop="type" :show-overflow-tooltip="true" align="center" label="抽奖类型" min-width="10%" :formatter="formateType">
      </el-table-column>
      <el-table-column prop="statusVal" :show-overflow-tooltip="true" align="center" label="抽奖状态" min-width="10%">
      </el-table-column>
      <el-table-column prop="num" :show-overflow-tooltip="true" align="center" label="参与人数" min-width="10%">
      </el-table-column>
      <el-table-column prop="isDistinct" :show-overflow-tooltip="true" align="center" label="是否去重" min-width="10%" :formatter="formateIsDistinct">
      </el-table-column>
      <el-table-column  align="center" label="操作" min-width="20%">
        <template slot-scope="scope">
          <el-button v-if="scope.row.status==33" type="text" size="mini" @click="pushScreen(scope.row)">推送</el-button>
          <el-button v-if="scope.row.status==33" type="text" size="mini" @click="deleteLuckyDraw(scope.row)">删除</el-button>
          <el-button v-if="scope.row.status==34 && scope.row.downTime>0" type="text" size="mini" disabled>{{scope.row.downTime}}s</el-button>
          <el-button v-if="scope.row.status==34 && scope.row.downTime<=0" type="text" size="mini" disabled>开奖中</el-button>
          <el-button v-if="scope.row.status==35" type="text" size="mini" @click="results(scope.row)">开奖结果</el-button>
          <el-button v-if="scope.row.status==35" type="text" size="mini" @click="deleteLuckyDraw(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="padding: 15px;text-align: right;">
      <el-pagination
        layout="total, prev, pager, next, jumper,sizes"
        @current-change="refreshPageRequest"
        :current-page="pageRequest.pageNum"
        :page-size="pageRequest.pageSize"
        :total="totalSize"
        :page-sizes="[10, 20, 30, 40]"
        @size-change="handleSizeChange"
      ></el-pagination>
    </div>
    <el-dialog
      title="创建抽奖"
      :visible.sync="dialogVisible"
      width="40%"
      @close="cancel"
      :close-on-click-modal="false"
      append-to-body>
      <el-row v-loading="editLoading">
        <el-form label-width="120px" size="mini" ref="dataForm" :model="dataForm" :rules="addRules" >
          <el-col :span="24">
            <el-form-item label="抽奖形式：" prop="type">
              <cy-select v-model="dataForm.type" :list="typeList"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抽奖名称：" prop="name">
              <el-input maxlength="30" placeholder="最多可编辑30个字"  v-model="dataForm.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="抽奖人数：" prop="num">
              <el-input maxlength="5"  placeholder="最多可输入99999人"  v-model="dataForm.num" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动时长：" prop="time">
              <cy-select v-model="dataForm.time" :list="timeList"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" >
            <el-form-item label="评论关键字：" prop="keyword" v-if="dataForm.type==1">
              <el-input v-model="dataForm.keyword" maxlength="20" placeholder="最多可编辑20个字" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="活动奖品：" prop="prizeType">
              <cy-select v-model="dataForm.prizeType" :list="prizeTypeList"></cy-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dataForm.prizeType==0">
            <el-form-item label="优惠券：" prop="couponName">
              <el-input placeholder="请选择优惠券" v-model="dataForm.couponName" disabled>
                <template slot="append">
                  <el-button type="primary" @click="couponDialogVisible = true">添加</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dataForm.prizeType==1">
            <el-form-item label="实物名称：" prop="goodsName">
              <el-input maxlength="30" placeholder="最多可编辑30个字" v-model="dataForm.goodsName" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="dataForm.prizeType==0||dataForm.prizeType==1">
            <el-form-item  :label="dataForm.prizeType==0?'优惠券图片：':'实物图片：'" prop="goodsImg">
              <cy-file-upload
                v-model="dataForm.goodsImg"
                @onSuccess="fileUploadSuccess"
              ></cy-file-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注：" prop="remark">
              <el-input maxlength="100" placeholder="最多可编辑100个字" v-model="dataForm.remark" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="去重：" prop="isDistinct">
              <el-checkbox true-label="1" false-label="0" v-model="dataForm.isDistinct" ></el-checkbox>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="24">
          <div style="text-align: center;">
            <el-button size="mini" @click="cancel">取消</el-button>
            <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
          </div>
        </el-col>
      </el-row>
      <el-dialog
        title="选择优惠券"
        :visible.sync="couponDialogVisible"
        width="80%"
        append-to-body>
        <div>
          <el-form label-width="100px" size="mini" :model="couponDataForm">
            <el-row>
              <el-col :span="6">
                <el-form-item label="优惠券批次：">
                  <el-input v-model="couponDataForm.batchId" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item>
                  <el-button type="primary" @click="couponQuery">查询</el-button>
                  <el-button @click="resetCoupon">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <el-table :data="couponTableData" height="300" v-loading="loading" :header-cell-style="headerCellStyle" :cell-style="cellStyle">
            <template slot="empty">
              <p>暂无数据</p>
            </template>
            <el-table-column prop="couponPlanId" :show-overflow-tooltip="true" align="center" label="方案编号" min-width="10%">
            </el-table-column>
            <el-table-column prop="couponName" :show-overflow-tooltip="true" align="center" label="方案名称" min-width="20%">
            </el-table-column>
            <el-table-column prop="id" :show-overflow-tooltip="true" align="center" label="优惠券批次" min-width="20%">
            </el-table-column>
            <el-table-column prop="maxOfferAmount" :show-overflow-tooltip="true" align="center" label="优惠最大金额" min-width="20%">
            </el-table-column>
            <el-table-column prop="batchStatus" :show-overflow-tooltip="true" align="center" label="状态" min-width="20%">
            </el-table-column>
            <el-table-column prop="applicantUsername" :show-overflow-tooltip="true" align="center" label="创建人" min-width="20%">
            </el-table-column>
            <el-table-column prop="createTime" :show-overflow-tooltip="true" align="center" label="创建时间" min-width="20%">
            </el-table-column>
            <el-table-column align="center" label="操作" min-width="20%">
              <template slot-scope="scope">
                <el-button type="text" size="mini" @click="selectCoupon(scope.row)">添加</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="padding: 15px;text-align: right;">
            <el-pagination
              layout="total, prev, pager, next, jumper,sizes"
              @current-change="refreshPageRequest2"
              :current-page="pageRequest2.pageNum"
              :page-size="pageRequest2.pageSize"
              :total="totalSize2"
              :page-sizes="[10, 20, 30, 40]"
              @size-change="handleSizeChange2"
            ></el-pagination>
          </div>
          <div style="text-align: center;">
            <el-button size="mini" type="primary">确认</el-button>
          </div>
        </div>
      </el-dialog>
    </el-dialog>
    <el-dialog
      title="开奖结果"
      :visible.sync="resultsDialogVisible"
      width="80%"
      append-to-body>
      <div>
        <el-table :data="resultsTableData" style="width: 100%;margin-top: 15px;" height="300" :header-cell-style="headerCellStyle" :cell-style="cellStyle">
          <template slot="empty">
            <p>暂无数据</p>
          </template>
          <el-table-column prop="number" :show-overflow-tooltip="true" align="center" label="开奖编号" min-width="20%">
          </el-table-column>
          <el-table-column prop="prizeName" :show-overflow-tooltip="true" align="center" label="奖品名称" min-width="20%">
          </el-table-column>
          <el-table-column prop="consignee" :show-overflow-tooltip="true" align="center" label="收货人" min-width="20%">
          </el-table-column>
          <el-table-column prop="phone" :show-overflow-tooltip="true" align="center" label="收货人手机" min-width="20%">
          </el-table-column>
          <el-table-column prop="uid" :show-overflow-tooltip="true" align="center" label="用户ID" min-width="20%">
          </el-table-column>
          <el-table-column prop="userName" :show-overflow-tooltip="true" align="center" label="用户名称" min-width="20%">
          </el-table-column>
          <el-table-column prop="prizeType" :show-overflow-tooltip="true" align="center" label="奖品类型" min-width="10%" :formatter="formatePrizeType">
          </el-table-column>
          <el-table-column prop="address" :show-overflow-tooltip="true" align="center" label="地址" min-width="20%">
          </el-table-column>
          <el-table-column prop="statusVal" :show-overflow-tooltip="true" align="center" label="状态" min-width="10%">
          </el-table-column>
        </el-table>
        <div style="padding: 15px;text-align: right;">
          <el-pagination
            layout="total, prev, pager, next, jumper,sizes"
            @current-change="refreshPageRequest3"
            :current-page="pageRequest3.pageNum"
            :page-size="pageRequest3.pageSize"
            :total="totalSize3"
            :page-sizes="[10, 20, 30, 40]"
            @size-change="handleSizeChange3"
          ></el-pagination>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import CySelect from "../../component/CySelect";
  import CyFileUpload from "../../component/CyFileUpload";
  export default {
    name: "liveControllerLuckyDrawManage",
    components: {
      CySelect,
      CyFileUpload
    },
    props:{
      data:{
        type: Object,
        default:()=>{}
      }
    },
    data() {
      return {
        rowId3:0,
        loading:false,
        editLoading:false,
        timer:'',
        pushDraw: '推送',  // 按钮里显示的内容
        totalTime: 60,
        dialogVisible: false,
        headerCellStyle:{
          'background-color': '#f1f1f1',
          'font-size':'12px',
          'color':'#000000'
        },
        cellStyle:{
          'font-size':'12px'
        },

        dataForm:{
          name:'',
          goodsName:'',
          num:'',
          time:'',
          keyword:'',
          type:'',
          prizeType:'',
          couponName:'',
          goodsImg:'',
          remark:'',
          isDistinct:0
        },
        findDataForm:{},
        couponDataForm:{},
        tableDataList:[],
        couponTableData:[],
        resultsTableData:[],
        pageRequest:{
          pageNum:1,
          pageSize:10
        },
        totalSize:10,
        pageRequest2:{

          pageNum:1,
          pageSize:10
        },
        totalSize2:10,
        pageRequest3:{
          pageNum:1,
          pageSize:10
        },
        totalSize3:10,
        status:0,
        typeList:[{
          value: 0,
          label: "点赞抽奖"
        },{
          value: 1,
          label: "评论抽奖"
        }],
        prizeTypeList:[{
          value: 0,
          label: "优惠券"
        },{
          value: 1,
          label: "实物奖品"
        }],
        timeList:[{
          value: 30,
          label: "30秒"
        },{
          value: 60,
          label: "1分钟"
        },{
          value: 120,
          label: "2分钟"
        },{
          value: 180,
          label: "3分钟"
        },{
          value: 240,
          label: "4分钟"
        },{
          value: 300,
          label: "5分钟"
        },{
          value: 600,
          label: "10分钟"
        },{
          value: 1800,
          label: "30分钟"
        },{
          value: 3600,
          label: "1小时"
        }],
        couponDialogVisible:false, // 优惠券模态框
        resultsDialogVisible:false, // 优惠券模态框
        parentData:{},
        addRules : {
          name: [
            { required: true, message: '抽奖名称不能为空', trigger: 'blur' },
          ],
          goodsName: [
            { required: true, message: '商品名称不能为空', trigger: 'blur' },
          ],
          num : [
            { required: true, message: '抽奖人数不能为空', trigger: 'blur' },
            {
              pattern: /^[1-9]\d*$/,
              message: '请输入大于0的整数',
              trigger: 'blur'
            }
          ],
          time : [
            { required: true, message: '活动时长不能为空', trigger: 'blur' },
            {
              pattern: /[1-9]\d{0,2}/,
              message: '请输入大于0的整数，少于999',
              trigger: 'blur'
            }
          ],
          keyword : [
            { required: true, message: '评论不能为空', trigger: 'blur' },
          ],
          type : [
            { required: true,  message: '请选择抽奖方式' ,trigger: 'change'},
          ],
          prizeType : [
            { required: true, message: '请选择奖品类别' ,trigger: 'change'},
          ],
          couponName : [
            { required: true, message: '请选择添加优惠券' ,trigger: 'change'},
          ],
          goodsImg : [
            { required: true, message: '请添加图片' ,trigger: 'change'},
          ],
        },
      }
    },
    mounted: function () {
      this.parentData = this.data
      this.findPage();
      this.init();
    },
    destroyed(){ // 页面销毁
      this.clearTimer()
    },
    methods: {
      clearTimer(){ // 清除定时器
        clearInterval(this.timer)
      },
      //时间初始化 倒计时开始
      init() {
        let i=0;
        this.timer = setInterval(() => {
          this.tableDataList.forEach((item,idx) => {
            if(item.status==34 && item.downTime>0){
              item.downTime = item.downTime - 1 <= 0 ? 0 : item.downTime - 1;
            }
          })
          this.tableDataList.forEach((item,idx) => {
            if(item.status==34 && item.downTime<=0){
              if(i==2){
                this.findPage();
                i=0;
              }
            }
          })
          if(i==5){
            this.findPage();
            i=0;
          }
          i++;
        },1000)
      },
      updateDataStatus(item){
        this.editLoading = true;
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/updateLiveLuckDrawStatus',
          method: 'post',
          params: item
        }).then(result => {
          let data = result.data;
          if (data && data.code === '0') {
            this.findPage();
            this.$forceUpdate();
          }
          this.$emit("pushScreen",item)
          this.editLoading = false;
        });
      },
      findPageById(item){
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/getLiveLuckDrawListById',
          method: 'get',
          params: item
        }).then(result => {
          let data = result.data;
          if (data && data.code === '0') {
            this_.tableDataList = data.data.rows;
            this.totalSize = data.data.total;
            this_.$forceUpdate();
          } else {
            this_.tableDataList = []
            this_.totalSize = 0
          }
          this_.dataListLoading = false
        });
      },
      //抽奖类型转换
      formateType(row, column, cellValue, index) {
        //抽奖类型  0 点赞抽奖 1 评论抽奖
        if (cellValue == '0') {
          return "点赞抽奖";
        } else if (cellValue == '1') {
          return "评论抽奖";
        }
        return "";
      },
      //抽奖类型转换
      formateIsDistinct(row, column, cellValue, index) {
        //抽奖类型  0 点赞抽奖 1 评论抽奖
        if (cellValue == '0') {
          return "否";
        } else if (cellValue == '1') {
          return "是";
        }
        return "";
      },
      formatePrizeType(row, column, cellValue, index) {
        //奖品类型  0 优惠券 1 实物 2 积分
        if (cellValue == '0') {
          return "优惠券";
        } else if (cellValue == '1') {
          return "实物";
        }else if (cellValue == '2') {
          return "积分";
        }
      },
      /*新增提交*/
      dataFormSubmit: function() {
        this.$refs.dataForm.validate(valid => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              this.editLoading = true;
              this.dataForm.liveId=this.parentData.id;
              this.dataForm.status=33;
              this.utils.request.liveRequest({
                url: '/api/v1/broadcast/updateLiveLuckDraw',
                method: 'post',
                params: this.dataForm
              }).then(result => {
                let data = result.data;
                if (data && data.code === '0') {
                  this.$refs.dataForm.resetFields();
                  this.findPage();
                  this.$forceUpdate();
                }
                this.editLoading = false;
              });
              this.dialogVisible = false;
            })
          }
        });
      },
      findPage(){
        let this_=this;
        if (this_.findDataForm == undefined || this_.findDataForm == null) {
          this_.findDataForm = {};
        }
        this_.findDataForm.liveId=this_.parentData.id;
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/getLiveLuckDrawList',
          method: 'get',
          params: this_.findDataForm
        }).then(result => {
          let data = result.data;
          if (data && data.code === '0') {
            this_.tableDataList = data.data.rows;
            this.totalSize = data.data.total;
            this_.$forceUpdate();
          } else {
            this_.tableDataList = []
            this_.totalSize = 0
          }
        });
      },
      deleteLuckyDraw(row){ //删除
        this.editLoading=true
        let id = row.id;
        this.$confirm("确定删除吗", "提示", {type:'warning'}).then(() => {
          this.utils.request.liveRequest({
            url: '/api/v1/broadcast/deleteLiveLuckDraw',
            method: 'post',
            params: {"id":id,"liveId":this.parentData.id}
          }).then(result => {
            let data = result.data;
            if (data && data.code == '0') {
              this.findPage();
              this.$message.success("删除成功");
            }else{
              this.$message.success("删除成功");
            }
          })
        })
      },
      //查看中奖结果
      findPageDrawResult(row){
        this.rowId3=row.id;
        let params={"drawId":row.id,"pageNum":this.pageRequest3.pageNum,"pageSize":this.pageRequest3.pageSize}
        let this_=this;
        this.utils.request.liveRequest({
          url: '/api/v1/broadcast/getLiveDrawRecordList',
          method: 'get',
          params: params
        }).then(result => {
          let data = result.data;
          if (data && data.code === '0') {
            this_.resultsTableData = data.data.rows;
            this.totalSize3 = data.data.total;
            this_.$forceUpdate();
          } else {
            this_.resultsTableData = []
            this_.totalSize3 = 0
          }
        });
      },
      /*图片相关*/
      handleRemove(file) {
        console.log(file);
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisibleImg = true;
      },
      handleDownload(file) {
        console.log(file);
      },
      handleAvatarSuccess(res, file) {
        this.dataForm.goodsImg = file.response.data;
      },
      /*图片相关*/
      reset(){
        this.dataForm = {}
      },
      reset2(){
        this.couponDataForm = {}
      },
      handleSizeChange: function (pageSize) {
        this.pageRequest.pageSize = pageSize;
        this.pageRequest.pageNum = 1;
        this.findPage();
      },
      refreshPageRequest: function (pageNum) {
        this.pageRequest.pageNum = pageNum;
        this.findPage();
      },
      handleSizeChange2: function (pageSize) {
        this.pageRequest2.pageSize = pageSize;
        this.pageRequest2.pageNum = 1;
        this.couponQuery();
      },
      refreshPageRequest2: function (pageNum) {
        this.pageRequest2.pageNum = pageNum;
        this.couponQuery();
      },
      handleSizeChange3: function (pageSize) {
        this.pageRequest3.pageSize = pageSize;
        this.pageRequest3.pageNum = 1;
        let row = {'id' :this.rowId3}
        this.findPageDrawResult(row)

      },
      refreshPageRequest3: function (pageNum) {
        this.pageRequest3.pageNum = pageNum;
        let row = {'id' :this.rowId3}
        this.findPageDrawResult(row)
      },
      cancel(){ // 取消

        this.$refs.dataForm.resetFields();
        this.dataForm.goodsImg='';
        this.dialogVisible = false
      },
      statusQuery(val){
        if(val!=-1){
          this.status=val;
          this.findDataForm.status=val;
        }else{
          this.status=0;
          this.findDataForm={};
        }
        this.findPage();
      },
      addCoupon(){
        this.couponDialogVisible = true
      },
      results(row){ // 开奖结果
        this.findPageDrawResult(row);
        this.resultsDialogVisible = true
      },
      pushScreen(row){ // 推屏

        let flag = this.tableDataList.find(value => {
          if(value.status==34 && value.downTime>0){
            return value
          }
        })
        if(flag){
          this.$message({message: "当前已经有一条在推送中了", type: "warning"});
        } else {
          row.status=34;
          this.updateDataStatus(row);
        }

      },
      resetCoupon(){ // 优惠券批次查询重置
        this.couponDataForm={};
        this.couponQuery();
      },
      couponQuery(){
        let batchId = this.couponDataForm.batchId
        if(batchId){
          this.loading = true
          this.utils.request.liveRequest({
            url: '/api/v1/broadcast/coupon/batch/'+batchId,
            method: 'get'
          }).then(result => {
            this.loading = false
            let data = result.data;
            if (data && data.code === '0') {
              this.couponTableData = data.data
              this.totalSize2 = data.data.total;
            }
          })
            .catch(() => {
              this.loading = false
            });
        } else {
          this.$message.info("请输入优惠券批次号");
        }
      },
      selectCoupon(row){ // 添加优惠券
        this.dataForm.couponId = row.id
        this.dataForm.couponName = row.couponName
        this.couponDialogVisible = false
      },
      fileUploadSuccess(res, file) { // 文件上传成功回调
        this.dataForm.goodsImg = res.data;
      },
    }
  }
</script>
<style scoped lang="scss">

</style>
